package com.lyk.coursearrange.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lyk.coursearrange.common.ServerResponse;
import com.lyk.coursearrange.common.log.annotation.Log;
import com.lyk.coursearrange.common.log.enums.OperationType;
import com.lyk.coursearrange.entity.*;
import com.lyk.coursearrange.entity.dto.DiagnosisDto;
import com.lyk.coursearrange.entity.dto.TemplateDto;
import com.lyk.coursearrange.service.CustomerInformationService;
import com.lyk.coursearrange.service.DiagnosisService;
import com.lyk.coursearrange.service.ScheduleService;
import com.lyk.coursearrange.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/diagnosis")
public class DiagnosisController {
    @Autowired
    private DiagnosisService diagnosisService;

    @Autowired
    private CustomerInformationService customerInformationService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private ScheduleService scheduleService;

    @PostMapping("/add")
    @Log(title = "添加诊断", operationType = OperationType.INSERT)
    public ServerResponse add(@RequestBody DiagnosisDto dto) {
        //修改客资状态
        LambdaUpdateWrapper<CustomerInformation> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CustomerInformation::getType, 3);
        wrapper.eq(CustomerInformation::getCustomerId, dto.getCustomerId());
        customerInformationService.update(wrapper);
        List diagnosisDetailArr = dto.getDiagnosisDetailArr();
        String jsonString = JSON.toJSONString(diagnosisDetailArr);
        List diagnosisTimeArr = dto.getDiagnosisTimeArr();
        String diagnosisTimeStr = JSON.toJSONString(diagnosisTimeArr);
        //保存到排课表中
        if (dto.getDiagnosisStatus() == 2L) {
            Schedule schedule = new Schedule();
            //查询排课中老师的时间是否有冲突
            LambdaQueryWrapper<Schedule> scheduleWrapper = new LambdaQueryWrapper<>();
            scheduleWrapper.eq(Schedule::getTeacherId,dto.getTeacherId());
            List<Schedule> list = scheduleService.list(scheduleWrapper);
            if (list.size() > 0){
                for (Schedule scheduleDb : list) {
                   if (scheduleDb.getCourseDate().equals(dto.getStartTimeDay())){
                       String courseDate = scheduleDb.getCourseDate();
                       String courseTimeOn = scheduleDb.getCourseTimeOn();
                       String courseEndTime = scheduleDb.getCourseEndTime();
                       String startTimeDay = dto.getStartTimeDay();
                       String startTime = dto.getStartTimeHour().get(0).toString().substring(0, 5);
                       String endTime = dto.getStartTimeHour().get(dto.getStartTimeHour().size() - 1).toString().substring(0, 5);
//                       DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                       DateTimeFormatter formatterDb = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                       //已经排课开始时间
                       LocalDateTime scheduleStartTime = LocalDateTime.parse(courseDate+" "+courseTimeOn,formatterDb);
                       //已经排课结束时间
                       LocalDateTime scheduleEndTime = LocalDateTime.parse(courseDate+" "+courseEndTime,formatterDb);
                       //前端传递的开始时间
                       LocalDateTime dStartTime = LocalDateTime.parse(startTimeDay+" "+startTime,formatterDb);
                       //前端传递的结束时间
                       LocalDateTime dEndTime = LocalDateTime.parse(startTimeDay+" "+endTime,formatterDb);
                       if ((dStartTime.isAfter(scheduleStartTime) )&& dEndTime.isBefore(scheduleEndTime)){
                           return ServerResponse.ofError("该时间段教师已有排课计划");
                       }
                   }
                }
            }
            schedule.setTeacherId(dto.getTeacherId());
            schedule.setCourseId(dto.getCategoryId());
            schedule.setCourseDate(dto.getStartTimeDay());
            schedule.setCourseTimeOn(dto.getStartTimeHour().get(0).toString().substring(0, 5));
            schedule.setCourseEndTime(dto.getStartTimeHour().get(dto.getStartTimeHour().size() - 1).toString().substring(0, 5));
            boolean save = scheduleService.save(schedule);
            LambdaQueryWrapper<Schedule> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Schedule::getTeacherId,dto.getTeacherId());
            queryWrapper.eq(Schedule::getCourseId,dto.getCategoryId());
            queryWrapper.eq(Schedule::getCourseTimeOn,dto.getStartTimeHour().get(0).toString().substring(0, 5));
            queryWrapper.eq(Schedule::getCourseEndTime,dto.getStartTimeHour().get(dto.getStartTimeHour().size() - 1).toString().substring(0, 5));
            Schedule scheduleOne = scheduleService.getOne(queryWrapper);
            boolean result =scheduleService.saveStudent(dto,scheduleOne.getScheduleId());
        }
        dto.setDiagnosisStatus(dto.getDiagnosisStatus());
        dto.setDiagnosisTime(diagnosisTimeStr);
        dto.setDiagnosisDetail(jsonString);
        boolean result = diagnosisService.save(dto);
        if (result) {
            return ServerResponse.ofSuccess("添加成功");
        } else {
            return ServerResponse.ofError("添加失败");
        }
    }

    @PostMapping("/getOne")
    @Log(title = "获取诊断根据id", operationType = OperationType.SELECT)
    public ServerResponse getById(@RequestBody DiagnosisDto diagnosisDto) {
        LambdaQueryWrapper<Diagnosis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Diagnosis::getCustomerId, diagnosisDto.getCustomerId());
        wrapper.eq(Diagnosis::getDiagnosisStatus, diagnosisDto.getDiagnosisStatus());
        Diagnosis diagnosis = diagnosisService.getOne(wrapper);
        DiagnosisDto dto = new DiagnosisDto();
        BeanUtils.copyProperties(diagnosis, dto);
        LambdaQueryWrapper<Teacher> teacherWrapper = new LambdaQueryWrapper<>();
        teacherWrapper.eq(Teacher::getId, dto.getTeacherId());
        Teacher teacher = teacherService.getOne(teacherWrapper);
        dto.setTeacherName(teacher.getRealname());
        return ServerResponse.ofSuccess(dto);
    }

    @PostMapping("/getList")
    public ServerResponse getList(@RequestBody DiagnosisDto diagnosisDto) {
        //查询客资id相等的诊断信息
        LambdaQueryWrapper<Diagnosis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Diagnosis::getCustomerId, diagnosisDto.getCustomerId());
        List<Diagnosis> diagnosisList = diagnosisService.list(wrapper);
        List<DiagnosisDto> diagnosisDtos = new ArrayList<>();
        //查询教师信息
        for (Diagnosis diagnosis : diagnosisList) {
            DiagnosisDto dto = new DiagnosisDto();
            BeanUtils.copyProperties(diagnosis, dto);
            LambdaQueryWrapper<Teacher> teacherWrapper = new LambdaQueryWrapper<>();
            teacherWrapper.eq(Teacher::getId, dto.getTeacherId());
            Teacher teacher = teacherService.getOne(teacherWrapper);
            dto.setTeacherName(teacher.getRealname());
            diagnosisDtos.add(dto);
        }
        return ServerResponse.ofSuccess(diagnosisDtos);
    }

    @PutMapping("/update")
    @Log(title = "修改诊断", operationType = OperationType.UPDATE)
    public ServerResponse update(@RequestBody DiagnosisDto dto) {
        List diagnosisDetailArr = dto.getDiagnosisDetailArr();
        String jsonString = JSON.toJSONString(diagnosisDetailArr);
        List diagnosisTimeArr = dto.getDiagnosisTimeArr();
        String diagnosisTimeStr = JSON.toJSONString(diagnosisTimeArr);
        dto.setDiagnosisDetail(jsonString);
        dto.setDiagnosisTime(diagnosisTimeStr);

        LambdaQueryWrapper<Diagnosis> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Diagnosis::getDiagnosisId, dto.getDiagnosisId());
        boolean result = diagnosisService.update(dto, wrapper);
        if (result) {
            return ServerResponse.ofSuccess("添加成功");
        } else {
            return ServerResponse.ofError("添加失败");
        }
    }
}
